package netty.lora;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import netty.DataResponse;
import netty.util.ByteUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @Author zhangtao
 * @create 2021/11/2 9:42
 */
public class LoraEncoder extends MessageToByteEncoder<Object> {
    private static final Logger LOG = LoggerFactory.getLogger(LoraEncoder.class);

    @Override
    protected void encode(ChannelHandlerContext arg0, Object o, ByteBuf byteBuf) throws Exception {
        byteBuf.writeBytes(this.encode(o));
    }

    public <T> ByteBuf encode(T obj) {
        DataResponse response = (DataResponse) obj;
        StringBuffer sb = new StringBuffer();
        sb.append("0000");
        sb.append(response.getStationId());
        sb.append(response.getLoraId());
        sb.append("012345678901234567890123456789");
        int length = response.getData().length() / 2;
        byte[] bytesLength = ByteUtil.intToByteArray(length);
        sb.append(ByteUtil.bytes2HexStr(bytesLength[0]));
        sb.append(ByteUtil.bytes2HexStr(bytesLength[1]));
        sb.append(response.getData());
        LOG.info("encode:" + sb);
        return Unpooled.copiedBuffer(ByteUtil.hextoBytes(sb.toString()));
    }
}